package summary;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;

public class DataReader {

	BufferedReader in = null;
	Vector<InstantData> instants = new Vector<InstantData>();
	Logger logger;
	
	// Format example
	// skip long node_id hex clock hex skew float_hex 

	public DataReader(String infile, String delimiters, String format,String outFile) {
		try {
			logger = new Logger(outFile);
			readFile(infile, delimiters, format);
			logger.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void readFile(String file, String delimiters, String format)
			throws FileNotFoundException {
		in = new BufferedReader(new FileReader(new File(file)));

		try {
			readMatrix(delimiters,format);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void readMatrix(String delimiters, String format) throws Exception {
		String line = null;	
		
		try {
			while ((line = in.readLine()) != null) {
			
				StringTokenizer tokenizer = new StringTokenizer(line, " :[]=x");
				StringTokenizer formatTokenizer = new StringTokenizer(format);

				while (tokenizer.hasMoreElements()) {
					
					String formatToken = formatTokenizer.nextToken();
					if(formatToken.compareTo("skip") == 0){
						if(formatTokenizer.nextToken().compareTo("long")==0){
							tokenizer.nextToken();
							continue;
						}
						else{
							throw new Exception("Format Inaccurate");
						}	
					}
					else {
						String s = tokenizer.nextToken();
						if(s.compareTo(formatToken)== 0 ){
							String dataType = formatTokenizer.nextToken();								
							
							if(dataType.compareTo("hex")==0){
								s = tokenizer.nextToken();
								s = tokenizer.nextToken();
								long longValue  = Long.valueOf(s, 16);
								
								if(formatToken.compareTo("nodeid")==0)
									if(longValue == 0)
										logger.println("");								
																	
								logger.print(" " + longValue);	
							}
							else if(dataType.compareTo("float_hex")==0){
								s = tokenizer.nextToken();
								s = tokenizer.nextToken();
								long longValue = Long.valueOf(s, 16);
								float floatValue =Float.intBitsToFloat((int)longValue);
								logger.print(" " + floatValue);
							}												
						}
						else{
							throw new Exception("Format Inaccurate");
						}		
						
						
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
